package com.yc.javaee.servlet.d0613;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

@WebServlet("/image.s")
public class ImageServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pic = req.getParameter("pic");

        // 获取应用上下文对象 全局唯一, 可以对全局资源做出解释
        ServletContext servletContext = this.getServletContext();
        String contentType = servletContext.getMimeType(pic);
        resp.setContentType(contentType);
        ServletOutputStream out = resp.getOutputStream();
        File file = new File("d:/" + pic);

        byte[] buffer = new byte[1024];
        int count;
        try(FileInputStream fis = new FileInputStream(file)){
            while((count = fis.read(buffer))>0){
                out.write(buffer,0,count);
            }
        }
    }
}
